using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class MesaController : BaseController<MesaViewModel, Mesa, int>
    {
        private IZonaService ZonaService { get; set; }
        public MesaController(IMesaService service, IZonaService zonaService)
            : base(service)
        {
            this.ZonaService = zonaService;
        }

        [HttpGet]
        public override ActionResult Index(int id = 0)
        {
            //- Cargamos el listado de zonas
            MesaViewModel model = new MesaViewModel { Zonas = ZonaService.GetAll().OrderBy(x => x.Descripcion) };

            //- Cargamos la mesa a editar
            if (id > 0) model.Entity = Service.Get(x => x.Id == id);

            return View(model);
        }

        [HttpGet]
        public override ActionResult List(string filter, int page = 1)
        {
            MesaViewModel model = new MesaViewModel
            {
                Entities = Service.Find(x => (filter == null || x.Nombre.Contains(filter)))
                      .OrderBy(y => y.Id)
                      .OrderBy(z => z.Zona.Descripcion)
                      .Skip((page - 1) * PageSize)
                      .Take(PageSize),

                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = Service.Find(x => (filter == null || x.Nombre.Contains(filter))).Count()
                }
            };
            model.Filter = filter;     
            return View(model);
        }

        public override ActionResult Save(MesaViewModel model)
        {
            //- Cargamos combo de zonas
            if (model.Zonas == null) model.Zonas = ZonaService.GetAll().OrderBy(x => x.Descripcion);

            //- Guardamos o actualizamos
            if (model.Entity.Id > 0)
                ErrorList = this.Service.Update(model.Entity);
            else
                ErrorList = this.Service.Add(model.Entity);                      

            return ShowError(model, ErrorList);
        }
    }
}
